const {
    success,
    fail
} = require('../utils/R')
const fs = require('fs')

function uploadController() {
    return {
        base: async function (ctx, next) {
            try {
                const file = ctx.request.files.file;	// 获取上传文件
                const reader = fs.createReadStream(file.filepath);	// 创建可读流
                const ext = file.originalFilename.split('.').pop(); // 获取上传文件扩展名
                const name = `static/${Math.random().toString()}.${ext}`
                const upStream = fs.createWriteStream(name); // 创建可写流
                reader.pipe(upStream);
                ctx.body = success(name, '保存成功')
            
            } catch (error) {
                console.log('----err----',error)
                ctx.body = fail(error)
            }
            next()
        },
    }
}

module.exports = uploadController()